package com.douyin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyin.entity.Captcha;
import com.douyin.exception.BaseException;
import com.douyin.mapper.CaptchaMapper;
import com.douyin.service.ICaptchaService;
import com.douyin.utils.DateUtil;
import com.google.code.kaptcha.Producer;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

@Service
public class CaptchaServiceImpl extends ServiceImpl<CaptchaMapper, Captcha> implements ICaptchaService {
    @Autowired
    private Producer producer;
    @Override
    public BufferedImage generateCaptcha(String uuId) {
        String code = producer.createText();
        Captcha captcha = new Captcha();
        captcha.setUuid(uuId);
        captcha.setCode(code);
        captcha.setExpireTime(DateUtil.addDateMinutes(new Date(),5));
        this.save(captcha);
        return producer.createImage(code);
    }

    @Override
    public boolean isValidate(Captcha captcha) {
        String code = captcha.getCode();
        captcha = this.getOne(new LambdaQueryWrapper<Captcha>().eq(Captcha::getUuid, captcha.getUuid()));
        if(captcha == null) throw new BaseException("uuid不存在");
        this.remove(new LambdaQueryWrapper<Captcha>().eq(Captcha::getUuid, captcha.getUuid()));
        if(!captcha.getCode().equals(code)){
            throw new BaseException("code错误");
        }
        if (captcha.getExpireTime().before(new Date(System.currentTimeMillis()))){
            throw new BaseException("图型验证码已过期");
        }
        return true;
    }
}
